/**
 *    Copyright 2009-2018 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.yinsin.jpabatis.mapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yinsin.jpabatis.config.Configuration;
import com.yinsin.jpabatis.reflection.MetaObject;
import com.yinsin.jpabatis.reflection.property.PropertyTokenizer;

/**
 * An actual SQL String got from an {@link SqlSource} after having processed any
 * dynamic content. The SQL may have SQL placeholders "?" and an list (ordered)
 * of an parameter mappings with the additional information for each parameter
 * (at least the property name of the input object to read the value from).
 * <p>
 * Can also have additional parameters that are created by the dynamic language
 * (for loops, bind...).
 *
 * @author Clinton Begin
 */
public class BoundSql {

	private final String sql;
	private final String countSql;
	private final List<ParameterMapping> parameterMappings;
	private final Object parameterObject;
	private final Map<String, Object> additionalParameters;
	private final MetaObject metaParameters;

	public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
		this.sql = sql;
		this.countSql = parseCountSql();
		this.parameterMappings = parameterMappings;
		this.parameterObject = parameterObject;
		this.additionalParameters = new HashMap<>();
		this.metaParameters = configuration.newMetaObject(additionalParameters);
	}
	
	private String parseCountSql() {
		if(null != sql && !sql.isEmpty()){
			StringBuffer csql = new StringBuffer("select count(*) from (");
			csql.append(sql);
			csql.append(") _temp_table ");
			return csql.toString();
		}
		return null;
	}

	public String getSql() {
		return sql;
	}
	
	public String getCountSql() {
		return countSql;
	}

	public List<ParameterMapping> getParameterMappings() {
		return parameterMappings;
	}

	public Object getParameterObject() {
		return parameterObject;
	}

	public boolean hasAdditionalParameter(String name) {
		String paramName = new PropertyTokenizer(name).getName();
		return additionalParameters.containsKey(paramName);
	}

	public void setAdditionalParameter(String name, Object value) {
		metaParameters.setValue(name, value);
	}

	public Object getAdditionalParameter(String name) {
		return metaParameters.getValue(name);
	}
}
